#include <string.h>
#include "third_party/fatfs/src/ff.h"
#include "config.h"
#include "ssidac.h"
#include "third_party/fatfs/src/ff.h"
#include "third_party/fatfs/src/diskio.h"

unsigned char configuration[16][3][200];
char effects[8][3] = { "BKO", "DLY", "ECO", "LPF", "HPF", "BPF", "NPF", "DEC", };

void getConfig(FIL *fp, CONFIG *config) {
	FRESULT fr;
	unsigned int read = 0;
	unsigned char buffer[20];
	do {
		fr = f_read(fp, &buffer, 20, (WORD *) &read);
		if (fr == FR_OK) {
			ParseCommands((unsigned char **) &buffer, config);
		}
	} while (read == 20);
}

void ParseCommands(unsigned char** buffer, CONFIG *config) {
	unsigned char *grid = "BT";
	unsigned char *fx = "F";
	unsigned char *slot = "S";
	unsigned char *hl = "HL";
	unsigned char *fr = "F";
	unsigned char numberChar[2];
	unsigned int number = 0;
	GRID button;
	FX effect;
	if (memcmp(&grid, buffer, 2)) {
		*buffer = *buffer + 2;
		memcpy(&numberChar, buffer, 1);
		number = ConvertHexToInteger(numberChar);
		button = config->buttons[number];
		config->buttons[number].button = number;
		*buffer = *buffer + 1;
		if (memcmp(&hl, buffer, 2)) {
			*buffer = *buffer + 2;
			if (*buffer[1] == 'l') {
				button.hl = latch;
			} else if (*buffer[1] == 'h') {
				button.hl = hatch;
			}
		} else if (memcmp(&fr, buffer, 1)) {
			*buffer = *buffer + 1;

		}
	} else if (memcmp(&fx, buffer, 1)) {
		*buffer = *buffer + 1;
		memcpy(buffer, &numberChar, 1);
		number = ConvertHexToInteger(numberChar);
		if (number == 1) {
			effect = config->firstFX;
		} else if (number == 2) {
			effect = config->secondFX;
		}
		if (*buffer[0] == '=') {
			strcpy((char *) effect.effect, "");

		}
	}
}

int ConvertHexToInteger(unsigned char number) {
	if (number == '1') {
		return 1;
	} else if (number == '2') {
		return 2;
	} else if (number == '3') {
		return 3;
	} else if (number == '4') {
		return 4;
	} else if (number == '5') {
		return 5;
	} else if (number == '6') {
		return 6;
	} else if (number == '7') {
		return 7;
	} else if (number == '8') {
		return 8;
	} else if (number == '9') {
		return 9;
	} else if (number == 'A') {
		return 10;
	} else if (number == 'B') {
		return 11;
	} else if (number == 'C') {
		return 12;
	} else if (number == 'D') {
		return 13;
	} else if (number == 'E') {
		return 14;
	} else if (number == 'F') {
		return 15;
	} else if (number == '0') {
		return 0;
	} else {
		return -1;
	}
}

int ConvertStringToInteger(unsigned char * number) {
	int output = 0;
	int temp = 0;
	int character;
	for (character = 0; character < strlen((char *) number); character++) {
		temp = ConvertHexToInteger(number[character]);
		output = output * 10;
		output = output + temp;
		temp = 0;
	}
	return output;
}
